import { setStore } from '@/libs'
import { setToken, getToken } from "@/libs/auth";
import http from '@/libs/http'

const TOKEN = 'token', USER = 'user',
IS_ADMIN = 'is_admin', ROLES = 'roles',
PERMISSIONS = 'permissions',
PERMISSIONS_RELATION = 'permissions_relation', ACCESS = 'access';

export default {
    state: {
        token: getToken(),
        user: null,
        roles: [],
        permissions: [],
        access: []
    },
    getters: {
        user: state => state.user,
        isAdmin: state => state.isAdmin,
        roles: state => state.roles,
        permissions: state => state.permissions,
        access: state => state.access
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
            setToken(token)
        },
        SET_USER: (state, data) => {
            state.user = data
            setStore({ name: USER, content: data, type: 'session' })
        },
        SET_IS_ADMIN: (state, data) => {
            state.isAdmin = data
            setStore({ name: IS_ADMIN, content: data, type: 'session' })
        },
        SET_ROLES: (state, data) => {
            state.roles = (data == undefined ? [] : data)
            setStore({ name: ROLES, content: data, type: 'session' })
        },
        SET_ACCESS(state, access) {
            state.access = (access == undefined ? [] : access)
            setStore({ name: ACCESS, content: access, type: 'session' })
        },

    },
    actions: {

        async handleLogin({commit, state}, data) {
            const loginRes = await http({ url: '/system/sysuser/login', method: 'POST', data })
            if(loginRes.status && loginRes.token != undefined) {
                commit('SET_TOKEN', loginRes.token)

                const userRes = await http({
                    url: '/system/sysuser/getUserInfoByToken',
                    method: 'GET',
                    params: {token: loginRes.token}
                })
                if(userRes.status) {
                    commit('SET_USER', userRes.user)
                    commit('SET_IS_ADMIN', userRes.user.superAdmin)
                    commit('SET_ROLES', userRes.roles)
                    commit('SET_ACCESS', userRes.access)
                }
            }
            return loginRes
        }

    }
}

